package com.zhongli.devplatform.service.impl.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhongli.devplatform.mapper.sys.ReadAddressMapper;
import com.zhongli.devplatform.po.sys.ReadAddressPO;
import com.zhongli.devplatform.service.imp.sys.ReadAddressService;
import com.zhongli.devplatform.service.imp.sys.ReadSystemParameterService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.vo.sys.AddressVO;
import com.zhongli.devplatform.vo.sys.RollToolAddress;
import com.zhongli.devplatform.vo.sys.RollToolResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.List;


@Service
public class AddressServiceImpl extends ServiceImpl<ReadAddressMapper, ReadAddressPO> implements ReadAddressService {

    @Autowired
    private ReadAddressMapper readAddressMapper;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private RestTemplate restTemplate;


    @Value("${dev-platform.cache-name}")
    private String cacheName;


    @Override
    public List<AddressVO> listTree() {

        List<ReadAddressPO> readAddressPOList = readAddressMapper.selectList(new QueryWrapper<ReadAddressPO>().isNull("parent_id"));
        List<AddressVO> addressVOList = BeanCopierUtil.copy(readAddressPOList, AddressVO.class);
        for (AddressVO addressVO : addressVOList) {
            listChildren(addressVO);
        }
        return addressVOList;
    }

    private void listChildren(AddressVO parent) {

        List<ReadAddressPO> readAddressPOList = readAddressMapper.selectList(new QueryWrapper<ReadAddressPO>().eq("parent_id", parent.getId()));
        if (readAddressPOList.isEmpty()) {
            return;
        }

        List<AddressVO> addressVOList = BeanCopierUtil.copy(readAddressPOList, AddressVO.class);
        parent.setChildren(addressVOList);
        for (AddressVO addressVO : addressVOList) {
            listChildren(addressVO);
        }
    }

    @Override
    @Transactional
    public void synchronizeData() {

        String apiURL = cacheManager.getCache(cacheName + ReadSystemParameterService.CACHE_KEY).get(" api:roll_tools_api", String::new);
        String appId = cacheManager.getCache(cacheName + ReadSystemParameterService.CACHE_KEY).get("api:roll_tools_api_app_id", String::new);
        String secret = cacheManager.getCache(cacheName + ReadSystemParameterService.CACHE_KEY).get("api:roll_tools_api_app_secret", String::new);

        String url = apiURL + "/address/list?app_id=" + appId + "&app_secret=" + secret;

        ResponseEntity<RollToolResult> responseEntity = restTemplate.getForEntity(URI.create(url), RollToolResult.class);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {

            RollToolResult result = responseEntity.getBody();
            if (result.getCode() == 1) {

                readAddressMapper.deleteAll();
                List<RollToolAddress> rollToolAddressList = result.getData();

                for (RollToolAddress rollToolAddress : rollToolAddressList) {

                    ReadAddressPO readAddressPO = new ReadAddressPO();
                    readAddressPO.setId(rollToolAddress.getCode());
                    readAddressPO.setName(rollToolAddress.getName());
                    readAddressMapper.insert(readAddressPO);

                    if (rollToolAddress.getPchilds() != null) {
                        listChildren(readAddressPO.getId(), rollToolAddress.getPchilds());
                    }
                    if (rollToolAddress.getCchilds() != null) {
                        listChildren(readAddressPO.getId(), rollToolAddress.getCchilds());
                    }

                }

                putCache();
            }
        }


    }

    @Override
    @PostConstruct
    public void putCache() {

        Cache.ValueWrapper valueWrapper = cacheManager.getCache(cacheName + CACHE_KEY).get("list");
        if (valueWrapper != null) {
            return;
        }

        cacheManager.getCache(cacheName + CACHE_KEY).put("list", listTree());

    }

    private void listChildren(String parentId, List<RollToolAddress> children) {
        if (null == children) {
            return;
        }
        for (RollToolAddress rollToolAddress : children) {
            ReadAddressPO readAddressPO = new ReadAddressPO();
            readAddressPO.setId(rollToolAddress.getCode());
            readAddressPO.setName(rollToolAddress.getName());
            readAddressPO.setParentId(parentId);
            readAddressMapper.insert(readAddressPO);

            if (rollToolAddress.getPchilds() != null) {
                listChildren(readAddressPO.getId(), rollToolAddress.getPchilds());
            }
            if (rollToolAddress.getCchilds() != null) {
                listChildren(readAddressPO.getId(), rollToolAddress.getCchilds());
            }

        }


    }
}
